using Audio;
using System;
using System.Collections.Generic;
using TMPro;
using UI.ExamplePanel;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[Serializable]
public class CardData
{
    public int id;
    public string name;
    public string effect;
    public int maxCount;
    public List<int> strength;
}

[Serializable]
public class CardList
{
    public List<CardData> cards;
}

public class Card : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public int id;
    [HideInInspector] public string cardName;
    [HideInInspector] public int maxCount;
    [HideInInspector] public string effect;
    public List<int> strength;
    [HideInInspector] public Image cardImage;

    public bool isDrag = false;
    public bool isView = false;

    private CanvasGroup canvasGroup;       // 控制透明度和射线检测
    private Transform originalParent;      // 初始父物体
    private int originalIndex;             // 初始 siblingIndex
    private Vector3 originalPosition;      // 初始位置
    private Canvas rootCanvas;


    [Header("UI管理")]
    public TextMeshProUGUI nameText;
    public TextMeshProUGUI effectText;
    //public TextMeshProUGUI typeText;
    public TextMeshProUGUI strengthMoodText;
    public TextMeshProUGUI strengthPowerText;

    public void SetCardData(CardData cd)
    {
        id = cd.id;
        cardName = cd.name;
        maxCount = cd.maxCount;
        effect = cd.effect;
        strength = cd.strength;

        nameText.text = cardName;
        effectText.text = effect;
        strengthMoodText.text = strength[0].ToString();
        strengthPowerText.text = strength[1].ToString();

        //cardImage.sprite = Resources.Load<Sprite>("Arts/Cards/" + cd.name);
    }

    public void SetCardData(Card c)
    {
        id = c.id;
        cardName = c.name;
        maxCount = c.maxCount;
        effect = c.effect;
        strength = c.strength;

        nameText.text = cardName;
        effectText.text = effect;
        strengthMoodText.text = strength[0].ToString();
        strengthPowerText.text = strength[1].ToString();
    }

    /// <summary>
    /// 生成只能查看的视图，不能对其做任何拖拽和出牌动作，用于点击使用完的卡牌查看或者因为某些条件要选择卡牌显示的视图（例如弃牌）
    /// </summary>
    /// <param name="c">对应卡片的引用</param>
    /// <param name="content"></param>
    public void SetCardView(Card c, Transform content)
    {
        isView = true;
        gameObject.transform.SetParent(content);
        SetCardData(c);
    }


    void Awake()
    {
        canvasGroup = GetComponent<CanvasGroup>();
        if (canvasGroup == null) canvasGroup = gameObject.AddComponent<CanvasGroup>();

        rootCanvas = GetComponentInParent<Canvas>().rootCanvas;
    }

    #region 拖拽逻辑
    // 拖拽开始
    public void OnBeginDrag(PointerEventData eventData)
    {
        if (isView) return;
        originalParent = transform.parent;
        originalIndex = transform.GetSiblingIndex();
        originalPosition = transform.position;

        canvasGroup.blocksRaycasts = false; // 让射线能穿透拖拽的卡牌

        // 临时放到最上层
        transform.SetParent(rootCanvas.transform, true);
        transform.SetAsLastSibling();
    }

    // 拖拽中
    public void OnDrag(PointerEventData eventData)
    {
        if (isView) return;
        isDrag = true;
        CardManager.Instance.draggedCard = this;
        CardManager.Instance.handCards.Remove(this);
        transform.position = eventData.position;
    }

    // 拖拽结束
    public void OnEndDrag(PointerEventData eventData)
    {
        if (isView) return;
        canvasGroup.blocksRaycasts = true;

        GameObject target = eventData.pointerEnter;
        Debug.Log($"当前条件为 {CardManager.Instance.CanAttack()}，不允许打出 ");
        if (target != null && target.CompareTag("DropZone") && CardManager.Instance.CanAttack() &&
            CardManager.Instance.CalculateCardCount(StoryCardManager.Instance.GetCardOrderByName(cardName)))
        {
            Debug.Log($"卡牌 {cardName} 被打出！发动效果！");
            ActivateEffect();

            // 这里可以选择销毁或隐藏
            Destroy(gameObject);
        }
        else
        {
            // 返回原位
            transform.SetParent(originalParent);
            transform.SetSiblingIndex(originalIndex);
            CardManager.Instance.handCards.Insert(originalIndex, this);
            transform.position = originalPosition;
        }
        isDrag = false;
        CardManager.Instance.draggedCard = null;
    }

    public void ReSetOnDragCard()
    {
        if (isView) return;
        if (CardManager.Instance.draggedCard == null) return;

        transform.SetParent(originalParent);
        transform.SetSiblingIndex(originalIndex);
        CardManager.Instance.handCards.Insert(originalIndex, this);
        transform.position = originalPosition;

        isDrag = false;
        CardManager.Instance.draggedCard = null;
    }
    #endregion

    // 发动效果
    private void ActivateEffect()
    {
        // TODO: 在这里写你卡牌效果的统一逻辑，比如修改数值、触发动画等
        var curState = GameManager.Instance.curState;
        Guest guest = CoreMechanismManager.Instance.GetCurrentGuest();

        AudioManager.Instance.PlaySFX("Card");
        CoreMechanismManager.Instance.canGiveCardNum--;

        guest.UpdateEmotion(this.strength, curState);
        CardManager.Instance.UseCard(this);
        GamePanel.Instance.UpdateGuestUI(guest);

        // 触发对话 根据玩家名字 + 卡牌 id 去跟 对话对应起来 ，播放相应对话
        //DialogManager.Instance.StartDialogueForCharacter(guest.name, this.id, GamePanel.Instance.transform);
    }
}
